<?php
namespace Admin\Controller;

use Think\Page;
use Think\Verify;

class AdminController extends BaseController {

    public function index(){
    	$res = $list = array();
    	$keywords = I('keywords');
		$fenbu_id = I('fenbu_id');
		if(session('fenbu_id')==0 && $fenbu_id){
			$fenbu_id=$fenbu_id;
		}else{
			$fenbu_id=\session('fenbu_id');
		}
    	if(empty($keywords)){
    		$res = D('admin')->where('fenbu_id='.$fenbu_id)->select();
    	}else{
    		$res = D()->query("select * from __PREFIX__admin where fenbu_id=".$fenbu_id." user_name like '%$keywords%' order by admin_id");
    	}
    	
    	$role = D('admin_role')->where('fenbu_id='.$fenbu_id)->getField('role_id,role_name');
    	
    	if($res ){
    		foreach ($res as $val){
    			$val['role'] =  $role[$val['role_id']];
    			$val['add_time'] = date('Y-m-d H:i:s',$val['add_time']);
    			$list[] = $val;
    		}
    	}
    // 	dump($res);
		$this->assign('fenbu_list',$this->fenbu_list);
    	$this->assign('list',$list);
        $this->display();
    }
    
    public function aaa(){
        dump(session());
        die;
        //12312312
        // $return_goods = M('return_goods')->select();
        
        // foreach ($return_goods as $k=>$v){
        //     if($v['points'] == 0){
        //         $order_goods = M('order_goods')->where('spec_key = "'.$v['spec_key'].'" and order_id='.$v['order_id'].' and goods_id='.$v['goods_id'])->getField('points');
        //         M('return_goods')->where('spec_key = "'.$v['spec_key'].'" and order_id='.$v['order_id'].' and goods_id='.$v['goods_id'])->save(['points'=>$order_goods]);
        //         dump($order_goods);
        //     }
            
        // }
        
        $order = M('order o')
        ->field('g.points,o.kou_price,o.order_id')
        ->join('ty_order_goods g on g.order_id = o.order_id','right')
        ->where('o.store_id = 11 and o.add_time >1752336000 and o.add_time < 1752422400 and kou_price = 0')
        ->select();
        dump($order);
        die;
        
        
        
        
        
        // $order_id = '68,73,137,147,180,185,202,204,208,244,293,301,307,339,345,440,487,508,523,550,565,577,600,632,654,659,684,702,708,719,724,730,736,794,824,838,845,866,879,894,911,912,919,934,949,950,978,1011,1018,1043,1052,1058,1065,1075,1093,1101,1108,1138,1145,1149,1162,1166,1210,1235,1254,1257,1278,1307,1317,1320,1338,1347,1349,1358,1377,1387,1399,1400,1431,1436,1450,1453,1459,1478,1506,1521,1526,1539,1545,1552,1570,1596,1601,1610,1637,1659,1673,1676,1682,1690,1693,1706,1708,1731,1750,1778,1779,1853,1877,1887,1889,1903,1916,1919,1927,1928,1969,1994,2058,2071,2082,2085,2094,2099,2115,2121,2124,2136,2151,2158,2167,2203,2220,2236,2251,2262,2266,2269,2273,2287,2294,2299,2306,2320,2327,2337,2340,2358,2404,2406,2410,2447,2458,2461,2473,2480,2482,2511,2537,2539,2543,2569,2573,2577,2602,2608,2633,2654,2662,2695,2707,2718,2745,2773,2775,2781,2801,2805,2815,2824,2830,2869,2873,2884,2893,2895,2896,2914,2931,2935,2939,2948,2975,2982,2984,3026';
        // // $order_id = '68';
        // $list = M('order')->where(['order_id'=>['in',$order_id]])->select();
        // foreach ($list as $k=>$v){
        //     $order_goods = M('order_goods')->where(['order_id'=>$v['order_id']])->select();
        //     $pricr = 0;
        //     foreach ($order_goods as $k=>$v){
        //         $pricr += sanwei(($v['member_goods_price']*$v['points']*$v['goods_num'])/100);
        //     }
        //     M('order')->where(['order_id'=>$v['order_id']])->save(['kou_price'=>$pricr]);
        // }
     
    }
    
//   public function goodscategorys(){
//         $list = M('goods_category')->where('level = 1')->select();
       
        
//         foreach ($list as $ks=>$v){
//             $b = M('goods_category')->where('parent_id = '.$v['id'])->select();
        
//             $c = '';
//             if(!empty($b)){
//                 foreach($b as $key=>$vals){
//                     $c .= $vals['name'].'、';
//                 }
//             }
    
//             $list[$ks]['cc'] = $c;
         
//         }
        
       
//         $strTable ='<table width="500" border="1">';
//         $strTable .= '<tr>';
//         $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">一级分类</td>';
//         $strTable .= '<td style="text-align:center;font-size:12px;" width="*">二级分类</td>';
//         $strTable .= '</tr>';


//         foreach($list as $k=>$val){
        
//             $strTable .= '<tr>';
//             $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['name'].'</td>';
//             $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['cc'].'</td>';
//             $strTable .= '</tr>';
//         }
//         $strTable .='</table>';
//         unset($list);
//         downloadExcel($strTable,'order');
//         exit();
//     }
    
      public function goodscategorys(){
        $list = M('goods_category')->where('image != "" ')->select();
        foreach ($list as $k=>$v){
            if(!empty($v['image'])){
                $headers = file_exists($v['image']);
                dump($headers);
                if(!file_exists($v['image'])) {;
                    $this->downloadImage('http://cdn.tlcwjsc.com'.$v['image']);
                }
            }
        }
    }
    
public function downloadImage($url)
    {
        $url = $url;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        $file = curl_exec($ch);
        curl_close($ch);
        $this->saveAsImage($url, $file);
    }

    public function saveAsImage($url, $file)
    {
        $filename = pathinfo($url, PATHINFO_BASENAME);
        $dirname = pathinfo(parse_url($url, PHP_URL_PATH), PATHINFO_DIRNAME);
        $path =   substr($dirname,1);
        $fullpath =  $path . '/' . $filename;
        // 如果目录不存在，则创建
        if(!is_dir($path)) {
            mkdir($path, 0777, true);
        }
        if(file_exists($fullpath)) {
            //$this->output->writeln("【已存在】输出路径" . $fullpath);
        } else {
            $resource = fopen($fullpath, 'a');
            fwrite($resource, $file);
            fclose($resource);
            //$this->output->writeln("【已保存】输出路径" . $fullpath);
        }
    }

	
    public function fenbu(){
    	$keywords = I('keywords')?I('keywords'):'';
        $res = M('fenbu a')
            ->field('a.*,b.user_name')
            ->join('ty_admin b on a.fenbu_master=b.admin_id','LEFT')
            ->where('a.fenbu_name like "%'.$keywords.'%"')
            ->order('a.fenbu_sort asc')->select();
        if(!empty($res)){
            foreach ($res as $k=>$v){
                $biaoshi_xian = M('users')->where(['fenbu_id'=>$v['fenbu_id']])->where('biaoshi_xian <> "" ')->group('biaoshi_xian')->getField('biaoshi_xian',true);
                sort($biaoshi_xian);
                $res[$k]['biaoshi_xian'] = join(',',$biaoshi_xian);
            }
        }
    	$this->assign('list',$res);
        $this->display();
    }
	
	public function edit_fenbu(){ //添加编辑分部 
		$role=M('admin')->select();
		if(IS_POST && I('fenbu_id')){
			M('fenbu')->where('fenbu_id='.I('fenbu_id'))->save([
				'fenbu_name'=>I('fenbu_name'),
				'fenbu_master'=>I('fenbu_master'),
				'fenbu_sort'=>I('fenbu_sort'),
				'independence'=>I('independence'),
			]);
		$this->success("操作成功",U('Admin/Admin/fenbu'));exit;
		}else if(IS_POST && empty(I('fenbu_id'))){ 
			M('fenbu')->add([
				'fenbu_name'=>I('fenbu_name'),
				'fenbu_master'=>I('fenbu_master'),
				'fenbu_sort'=>I('fenbu_sort'),
				'independence'=>I('independence'),
				'fenbu_time'=>\time()
			]);
		$this->success("操作成功",U('Admin/Admin/fenbu'));exit;
		}

		if(I('fenbu_id')){
            $info=M('fenbu')->where('fenbu_id='.I('fenbu_id'))->find();
            $this->assign('info',$info);
        }

		$this->assign('role',$role);
	    $this->display();
	}
    /**
     * 地区绑定线路
     * @return void
     */
    public function area_b1()
    {
        $area_id = I('fenbu_id', 0);

            if (IS_POST) {
                $post_b1 = I('b1');
                $post_area_id = I('fenbu_id');
                $b1 = M('area_b1')->where(['fenbu_id' => $post_area_id])->getField('b1', true);
               
                if ($b1) { //先清除之前的设置

                    M('area_b1')->where(['fenbu_id' => $area_id])->delete();
                    M('users')->where(" `biaoshi_xian` in ('" . implode("','", $b1) . "')")->save(['fenbu_id' => 1]);
                }
                //重新绑定
                if ($post_b1) {
                    foreach ($post_b1 as $item) {
                        M('area_b1')->add(['fenbu_id' => $area_id, 'b1' => $item]);
                        M('users')->where('biaoshi_xian = "' . $item . '" ')->save(['fenbu_id' => $post_area_id]);
                    }
                }
                $this->success("操作成功", U('Admin/Admin/fenbu'));
                exit;
            }


            $b1 = M('area_b1')->where(['fenbu_id' => $area_id])->getField('b1', true);
            $b1s = M('area_b1')->getField('b1', true);
            // dump($b1s);
            $b1 = $b1 ?? [];
            $b1s = $b1s ?? [];
            $user_b1 = M('users')->where("biaoshi_xian <> ''")->cache(true, TPSHOP_CACHE_TIME)->group('biaoshi_xian')->getField('biaoshi_xian', true);
            sort($user_b1);
            $no_list = [];
            // dump($user_b1);
            foreach ($user_b1 as $item) {
                // dump($item);die;
                if (!in_array($item, $b1s)) {
                    $no_list[] = $item;
                }
            }
            $info = M('fenbu')->where('fenbu_id=' . $area_id)->find();
            $no_list = array_merge($b1, $no_list);
            $no_list = array_values($no_list);
            $this->assign('b1', $b1);
            $this->assign('info', $info);
            $this->assign('no_list', $no_list);
            $this->assign('area_id', $area_id);
        $this->display();
    }
        public function admin_info(){
    	$admin_id = I('get.admin_id',0);
    	if($admin_id){
    		$info = D('admin')->where("admin_id=$admin_id")->find();
                $info['password'] =  "";
    		$this->assign('info',$info);
    	}
		
    	$act = empty($admin_id) ? 'add' : 'edit';
    	$this->assign('act',$act);
    	$role = D('admin_role')->where('1=1 and fenbu_id='.\session('fenbu_id'))->select();
		$this->assign('fenbu_list',$this->fenbu_list);
    	$this->assign('role',$role);
    	$this->display();
    }
    
    public function adminHandle(){
    	$data = I('post.');
    	if(empty($data['password'])){
    		unset($data['password']);
    	}else{
    		$data['password'] = encrypt($data['password']);
    	}
    	if($data['act'] == 'add'){
    		unset($data['admin_id']);
    		$data['add_time'] = time();
    		if(D('admin')->where("user_name='".$data['user_name']."'")->count()){
    			$this->error("此用户名已被注册，请更换",U('Admin/Admin/admin_info'));
    		}else{
				$pd=M('admin_role')->where('fenbu_id='.$data['fenbu_id'])->find();
				if(empty($pd)){
					$roles=M('admin_role')->field('role_name,act_list,role_desc') ->where('fenbu_id=0')->select();
					foreach($roles as $vs){
						M('admin_role')->add([
							'role_name'=>$vs['role_name'],
							'act_list'=>$vs['act_list'],
							'role_desc'=>$vs['role_desc'],
							'fenbu_id'=>$data['fenbu_id']
						]); //初始化权限组
					}
					$r = M('admin')->add($data);
				}else{
					$r = M('admin')->add($data);
				}
    		}
    	}
    	
    	if($data['act'] == 'edit'){
    		$r = D('admin')->where('admin_id='.$data['admin_id'])->save($data);
    	}
    	
        if($data['act'] == 'del' && $data['admin_id']>1){
    		$r = D('admin')->where('admin_id='.$data['admin_id'])->delete();
    		exit(json_encode(1));
    	}
    	
    	if($r){
    		$this->success("操作成功",U('Admin/Admin/index'));
    	}else{
    		$this->error("操作失败",U('Admin/Admin/index'));
    	}
    }

    //shadow safe
	public function mysafety(){
		if(\session('admin_info') && empty(session('token')) && I('get.action')=='mysafe' && I('get.tt')>100){
			$admin_info=\session('admin_info');
			session('admin_id',$admin_info['admin_id']);
			session('act_list',$admin_info['act_list']);
			session('mystore_id',$admin_info['store_id']);
			session('role_id',$admin_info['role_id']);
			session('fenbu_id',$admin_info['fenbu_id']);
			session('print_t',$admin_info['print_t']);
			session('independence',$admin_info['independence']);
			$last_login_time = M('admin_log')->where("admin_id = ".$admin_info['admin_id']." and log_info = '后台登录'")->order('log_id desc')->limit(1)->getField('log_time');
			session('last_login_time',$last_login_time);
			adminLog('后台登录',__ACTION__);
			if($admin_info['user_name']=='HZD'){
				session('super','shadow');
			}
			echo '<script>top.location.href = "/Admin/index/index";</script>';
		}else{
			session(null);cookie(null);
			echo '<script>top.location.href = "/Admin/Admin/mysafety?action=mysafes";</script>';}
	exit;
	}
    
    /*
     * 管理员登陆
     */
    public function login(){
        if(session('?admin_id') && session('admin_id')>0){
             $this->error("您已登录",U('Admin/Index/index'));
        }
      
        if(IS_POST){
            /* $verify = new Verify();
            if (!$verify->check(I('post.vertify'), "admin_login")) {
            	exit(json_encode(array('status'=>0,'msg'=>'验证码错误')));
            } */
            $condition['user_name'] = I('post.username');
            $condition['password'] = I('post.password');
			$ddee = I('post.ddee');	
            if(!empty($condition['user_name']) && !empty($condition['password']) && !empty($ddee)){
                 $condition['password'] = encrypt($condition['password']);
               	$admin_info = M('admin a')->field('a.*,b.role_name,b.act_list')->join('ty_admin_role b ON a.role_id=b.role_id')->where($condition)->find();
                if(is_array($admin_info)){
                    session('admin_info',$admin_info); //shadow safe
					session('token',md5(C('token_code')));
					$url = '/Admin/Admin/login?tokens=ZdfsdSae'; //shadow safe end
                    //$url = session('from_url') ? session('from_url') : U('Admin/Index/index');
                    exit(json_encode(array('status'=>1,'url'=>$url)));
                }else{
                    exit(json_encode(array('status'=>0,'msg'=>'账号密码不正确')));
                }
				//shadow safe
				$validate=\explode("Shadow",$ddee);
				$dd=\json_decode(\base64_decode(\base64_decode(ltrim($validate[0],"T"))),true);
				$ee=\json_decode(\base64_decode(\base64_decode(substr($validate[1],1))),true);
				//exit(json_encode(array('status'=>0,'msg'=>$ee["wstar"].'-'.$dd["lstar"])));exit;

				if($ee["wstar"]>$dd["lstar"] && $ee["wstar"]<$dd["lend"] && $ee["hstar"]>$dd["tstar"] && $ee["hstar"]<$dd["tend"]){
				
					$nows1=strtotime(date('Y-m-d H:i').":00");
					//$nows2=strtotime(date('Y-m-d H:i', strtotime('+1minute')).":00");
					$jsnow=strtotime(date('Y-m-d H:i',$ee["tt"]/1000));
				
				if($jsnow!=$nows1){
					session(null);cookie(null);
					exit(json_encode(array('status'=>0,'msg'=>'非安全登陆，记录ip！')));
				}

				//end shadow

                $condition['password'] = encrypt($condition['password']);
               	$admin_info = M('admin a')->field('a.*,b.role_name,b.act_list')->join('ty_admin_role b ON a.role_id=b.role_id')->where($condition)->find();
                if(is_array($admin_info)){
                    session('admin_info',$admin_info); //shadow safe
					session('token',md5(C('token_code')));
					$url = '/Admin/Admin/login?tokens=ZdfsdSae'; //shadow safe end
                    //$url = session('from_url') ? session('from_url') : U('Admin/Index/index');
                    exit(json_encode(array('status'=>1,'url'=>$url)));
                }else{
                    exit(json_encode(array('status'=>0,'msg'=>'账号密码不正确')));
                }
				}else{
					session(null);cookie(null);
					exit(json_encode(array('status'=>0,'msg'=>'非安全登陆，已记录ip！')));
					}
            }else{
				session(null);
                exit(json_encode(array('status'=>0,'msg'=>'请填写账号密码')));
            }
        }

        $this->display();
    }
    
    /**
     * 退出登陆
     */
    public function logout(){
        session_unset();
        session_destroy();
        $this->success("退出成功",U('Admin/Admin/login'));
    }
    
    /**
     * 验证码获取
     */
    public function vertify()
    {
        $config = array(
            'fontSize' => 30,
            'length' => 4,
            'useCurve' => true,
            'useNoise' => false,
        	'reset' => false
        );    
        $Verify = new Verify($config);
        $Verify->entry("admin_login");
    }
    
    public function role(){
    	$list = D('admin_role a')->field('a.*,b.fenbu_name')->join('ty_fenbu b on a.fenbu_id=b.fenbu_id','LEFT')->where('a.fenbu_id='.\session('fenbu_id'))->order('a.role_id desc')->select();
    	$this->assign('list',$list);
    	$this->display();
    }
    
    public function role_info(){
    	$role_id = I('get.role_id');
    	$tree = $detail = array();
    	if($role_id){
    		$detail = M('admin_role')->where("role_id=$role_id")->find();
    		$detail['act_list'] = explode(',', $detail['act_list']);
    		$this->assign('detail',$detail);
    	}
    	$right = M('system_menu')->order('id')->select();
    	foreach ($right as $val){
    		if(!empty($detail)){
    			$val['enable'] = in_array($val['id'], $detail['act_list']);
    		}
    		$modules[$val['group']][] = $val;
    	}
    	//权限组
    	$group = groupMenu();
		//echo \json_encode($modules);shadow
    	$this->assign('group',$group);
    	$this->assign('modules',$modules);
    	$this->display();
    }
    
    public function roleSave(){
    	$data = I('post.');$data['data']['fenbu_id']=I('fenbu_id');
    	$res = $data['data'];
    	$res['act_list'] = is_array($data['right']) ? implode(',', $data['right']) : '';
    	if(empty($data['role_id'])){
    		$r = D('admin_role')->add($res);
    	}else{
    		$r = D('admin_role')->where('role_id='.$data['role_id'])->save($res);
    	}
    	if($r){
    		adminLog('管理角色',__ACTION__);
    		$this->success("操作成功!",U('Admin/Admin/role_info',array('role_id'=>$data['role_id'])));
    	}else{
    		$this->success("操作失败!",U('Admin/Admin/role'));
    	}
    }
    
    public function roleDel(){
    	$role_id = I('post.role_id');
    	$admin = D('admin')->where('role_id='.$role_id)->find();
    	if($admin){
    		exit(json_encode("请先清空所属该角色的管理员"));
    	}else{
    		$d = M('admin_role')->where("role_id=$role_id")->delete();
    		if($d){
    			exit(json_encode(1));
    		}else{
    			exit(json_encode("删除失败"));
    		}
    	}
    }
    
    public function log(){
    	$Log = M('admin_log');
    	$p = I('p',1);
    	$logs = $Log->join('__ADMIN__ ON __ADMIN__.admin_id =__ADMIN_LOG__.admin_id')->order('log_time DESC')->page($p.',20')->select();
    	$this->assign('list',$logs);
    	$count = $Log->where('1=1')->count();
    	$Page = new \Think\Page($count,20);
    	$show = $Page->show();
    	$this->assign('page',$show); 	
    	$this->display();
    }

	/**
	 * 供应商列表
	 */
	public function supplier()
	{
		$supplier_model = M('');
		$db_prefix = C('DB_PREFIX');
		$supplier_count = $supplier_model->table($db_prefix.'suppliers')->where('')->count();
		$page = new Page($supplier_count, 10);
		$show = $page->show();
		$supplier_list = $supplier_model
				->field('s.*,a.admin_id,a.user_name')
				->table($db_prefix.'suppliers s')
				->join('LEFT JOIN '.$db_prefix.'admin AS a ON a.suppliers_id = s.suppliers_id')
				->where('')
				->limit($page->firstRow, $page->listRows)
				->select();
		$this->assign('list', $supplier_list);
		$this->assign('page', $show);
		$this->display();
	}

	/**
	 * 供应商资料
	 */
	public function supplier_info()
	{
		$suppliers_id = I('get.suppliers_id', 0);
		if ($suppliers_id) {
			$db_prefix = C('DB_PREFIX');
			$suppliers_model = M('suppliers');
			$info = $suppliers_model
					->field('s.*,a.admin_id,a.user_name')
					->table($db_prefix.'suppliers s')
					->join('LEFT JOIN '.$db_prefix.'admin AS a ON a.suppliers_id = s.suppliers_id')
					->where(array('s.suppliers_id' => $suppliers_id))
					->find();
			$this->assign('info', $info);
		}
		$act = empty($suppliers_id) ? 'add' : 'edit';
		$this->assign('act', $act);
		$admin = M('admin')->field('admin_id,user_name')->where('1=1')->select();
		$this->assign('admin', $admin);
		$this->display();
	}

	/**
	 * 供应商增删改
	 */
	public function supplierHandle()
	{
		$data = I('post.');
		$suppliers_model = M('suppliers');
		//增
		if ($data['act'] == 'add') {
			unset($data['suppliers_id']);
			$count = $suppliers_model->where("suppliers_name='" . $data['suppliers_name'] . "'")->count();
			if ($count) {
				$this->error("此供应商名称已被注册，请更换", U('Admin/Admin/supplier_info'));
			} else {
				$r = $suppliers_model->add($data);
				if (!empty($data['admin_id'])) {
					$admin_data['suppliers_id'] = $suppliers_model->getLastInsID();
					M('admin')->where(array('suppliers_id' => $admin_data['suppliers_id']))->save(array('suppliers_id' => 0));
					M('admin')->where(array('admin_id' => $data['admin_id']))->save($admin_data);
				}
			}
		}
		//改
		if ($data['act'] == 'edit' && $data['suppliers_id'] > 0) {
			$r = $suppliers_model->where('suppliers_id=' . $data['suppliers_id'])->save($data);
			if (!empty($data['admin_id'])) {
				$admin_data['suppliers_id'] = $data['suppliers_id'];
				M('admin')->where(array('suppliers_id' => $admin_data['suppliers_id']))->save(array('suppliers_id' => 0));
				M('admin')->where(array('admin_id' => $data['admin_id']))->save($admin_data);
			}
		}
		//删
		if ($data['act'] == 'del' && $data['suppliers_id'] > 1) {
			$r = $suppliers_model->where('suppliers_id=' . $data['suppliers_id'])->delete();
			M('admin')->where(array('suppliers_id' => $data['suppliers_id']))->save(array('suppliers_id' => 0));
		}

		if ($r !== false) {
			$this->success("操作成功", U('Admin/Admin/supplier'));
		} else {
			$this->error("操作失败", U('Admin/Admin/supplier'));
		}
	}
}